package com.biqee.service.tb.impl;

import java.io.InputStream;

import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.biqee.model.TaobaoShopParseResult;
import com.biqee.service.tb.TaobaoBShopParseService;
import com.biqee.service.tb.TaobaoCShopParseService;
import com.biqee.service.tb.TaobaoShopParseService;
import com.biqee.util.JsoupUtil;


public class TaobaoShopParseServiceImpl implements TaobaoShopParseService {
	private static final Logger logger = Logger.getLogger(TaobaoShopParseServiceImpl.class);
	
	@Override
	public TaobaoShopParseResult parse(InputStream inputStream,
			String charsetName, String pageUrl) {
		Document doc = JsoupUtil.createDocument(inputStream, charsetName, pageUrl);
		if(doc == null) {
			logger.error("create doc failed. charsetName: " + charsetName + ", url: " + pageUrl);
			return null;
		}
		
		return parse(doc);
	}

	@Override
	public TaobaoShopParseResult parse(String html) {
		Document doc = JsoupUtil.createDocument(html);
		if(doc == null) {
			logger.error("create doc failed.");
			return null;
		}
		
		return parse(doc);
	}

	private TaobaoShopParseResult parse(Document doc) {
		boolean isBShopDocument = isBShopDocument(doc);
		if(isBShopDocument) {
			return taobaoBShopParseService.parse(doc);
		} else {
			return taobaoCShopParseService.parse(doc);
		}
	}
	
	private boolean isBShopDocument(Document doc) {
		Elements divElements = doc.select("div");
		for(Element e : divElements) {
			String id = e.attr("id");
			if("mall-shop".equals(id)) {
				return true;
			}
		}
		
		return false;
	}
	
	private TaobaoCShopParseService taobaoCShopParseService;

	
	private TaobaoBShopParseService taobaoBShopParseService;

	public void setTaobaoCShopParseService(
			TaobaoCShopParseService taobaoCShopParseService) {
		this.taobaoCShopParseService = taobaoCShopParseService;
	}

	public void setTaobaoBShopParseService(
			TaobaoBShopParseService taobaoBShopParseService) {
		this.taobaoBShopParseService = taobaoBShopParseService;
	}

	
	
}
